import 'package:bruno/bruno.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:mobile_scanner/mobile_scanner.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:yt_devops/components/log_utils.dart';
import 'package:yt_devops/configs.dart';
import 'package:yt_devops/pages/devices/device_add/scan_device_result/scan_device_result_model.dart';
import 'package:yt_devops/pages/devices/device_list/device_list_model.dart';
import 'package:yt_devops/routers/router_path.dart';
import 'package:yt_devops/services/device/device_sevices.dart';
import 'package:yt_devops/styles/styles.dart';

import '../../../../resources/str_res_keys.dart';

class DeviceScannerController extends GetxController
    with GetTickerProviderStateMixin {
  MobileScannerController scanController = MobileScannerController(
    torchEnabled: false,
  );

  DeviceServices services = Get.find();

  bool isLoading = false;
  bool scanFail = false;//扫描失败
  late Animation<double> animation;
  late AnimationController _anicontroller;

  //起始之间的线性插值器 从 0.05 到 0.95 百分比。
  final Tween<double> _rotationTween = Tween(begin: 0.05, end: 0.95);
  late int siteId;
  bool cameraIsDenied = true;
  Color backgroundColor = Colors.transparent;
  @override
  void onInit() {
    super.onInit();
    Log.d('DeviceScannerController===');
    requestCameraPermission();
    siteId = Get.arguments['siteId'];
    // cameraIsDenied = Get.arguments['cameraIsDenied'];
    _anicontroller = AnimationController(
      vsync: this, //实现 TickerProviderStateMixin
      duration: Duration(seconds: 3), //动画时间 3s
    );

    animation = _rotationTween.animate(_anicontroller)
      ..addListener(() => update())
      ..addStatusListener((status) {
        if (status == AnimationStatus.completed) {
          _anicontroller.repeat();
        } else if (status == AnimationStatus.dismissed) {
          _anicontroller.forward();
        }
      });

    _anicontroller.repeat();
  }

///检查相机权限
  Future<void> requestCameraPermission() async {
    final status = await Permission.camera.request();
    Log.d('status===' + status.toString());
    if (status == PermissionStatus.denied ||
        status == PermissionStatus.permanentlyDenied) {
      // 摄像头权限被拒绝
      cameraIsDenied = true;
      BrnDialogManager.showConfirmDialog(
          Get.context!,
          cancel: '我知道了',
          confirm: '前往设置',
          title: '相机权限未开启',
          onCancel: () => Get.back(),
          onConfirm: () {
            openAppSettings();
            Get.back();
          },
          barrierDismissible:false
      );
    } else {
      // 摄像头权限没被拒绝
      cameraIsDenied = false;
    }
    update();
  }
  // Future<void> requestCameraPermission() async {
  //   Log.d('相机权限未开启===');
  //   final status = await Permission.camera.request();
  //   Log.d('status==1111=' + status.toString());
  //   // if (status == PermissionStatus.permanentlyDenied ||status == PermissionStatus.denied) {
  //
  //     Log.d('相机权限未开启===' + status.toString());
  //     // 摄像头权限被拒绝
  //     BrnDialogManager.showConfirmDialog(
  //       Get.context!,
  //       cancel: '我知道了',
  //       confirm: '前往设置',
  //       title: '相机权限未开启',
  //       onCancel: () => Get.back(),
  //       onConfirm: () {
  //       openAppSettings();
  //         Get.back();
  //       },
  //     );
    // }
  // }

  ///通过sn码去查询设备是否绑定
  getDevice(String sn) => Configs.httpClient.requestWithLoading(() async {
        isLoading = true;
        var param = {'sn': sn};
        Log.d('data=sn=' + sn.toString());

        var data = await services.getDeviceBySn(param,onError: (error){
          Get.offNamed(RouterPath.deviceScanFail, arguments: {
            'siteId':siteId,
            'message':error.message
          });
          return true;
        });
        if (data != null) {
          var device = DeviceListModel.fromJson(data);
          Get.offNamed(RouterPath.accessDeviceByScanner, arguments: {
            'device':device,
            'siteId':siteId
          });
        }
      }, showLoading: false);

  @override
  void onReady() {

  }

  @override
  void onClose() {
    _anicontroller.dispose();
  }
}
